<?php
namespace Lavender;

class WebService extends WebPage
{
	const CONTENT_TYPE = 'application/json; charset=utf-8';
    protected $without_sign_actions = array();

	public function render($__data__ = null, $__view__ = null)
	{
		//get friend message
		if (isset($__data__['code']) && $__data__['code'] > 0) {
			$msg = isset($__data__['msg'])?$__data__['msg']:'';
			if(!empty($msg))
			{
				$__data__['msg'] = $msg;
			}
		}

		//json
		//$__data__['code'] = (string)$__data__['code'];
		$response = json_encode($__data__, JSON_UNESCAPED_UNICODE);

		if (!empty($_GET['callback']) ) {
			//jsonp
			if (!preg_match('/^[a-z0-9\._]+$/i', $_GET['callback']) ) {
				throw new Exception("callback error,callback:{$_GET['callback']}", Errno::PARAM_INVALID);
			}

			$response = $_GET['callback'] . "($response)";

			//for iframe submit mode
			if (substr($_GET['callback'], 0, 7) == 'parent.') {
				header('Content-Type: text/html; charset=utf-8');
				$response = "<script type='text/javascript'>$response</script>";
			}
		}
		echo $response;
		//write session flow
		$this->session_flow($__data__);
	}

	protected function session_flow($response)
	{
		if(!empty($_POST)){
			$uid = isset($this->uid) ? $this->uid : 0;
			$ip = $this->get_client_ip();
			$url = $this->get_current_url();
			$post = $_POST;
			if(isset($post['password'])){
				unset($post['password']);
			}
            $input = self::get_raw_body();
			$content = date('Y-m-d H:i:s') . "\t{$ip}\t{$uid}\t{$url}\tPOST:" . json_encode($post, JSON_UNESCAPED_UNICODE) . "\tinput:{$input}\tRESP:" . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n";

			$filename = $response['code'] ? 'error' : '';
			Core::log('flow', $content, $filename);
		}
	}

	public function render_error($msg, $code = 401)
	{
        $this->header_content_type("application/json");
		$data = array(
			'code' => $code,
			'msg' => $msg,
			'data' => '',
		);
        $this->session_flow($data);
		return $this->render($data);
	}

    public function success($msg = '', $data = null){
        $this->header_content_type("application/json");
        return parent::success($msg,$data);
    }

    public function error($msg = '', $code = -1){
        $this->header_content_type("application/json");
        return parent::error($msg,$code);
    }


}
